package util;

import java.sql.*;

public class DBUtil {
    //0.定义数据库主机，数据库，字符集，用户名，密码
   static String url ="jdbc:mysql:///CompanyManager?characterEncoding=utf8";
   static String user="root";
   static String pwd="root";



    //1.注册驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //2.获取连接对象
    public  static Connection getCoon() throws SQLException {
        Connection conn = DriverManager.getConnection(url, user, pwd);
        return conn;
    }
    //3.通用查询方法
    public static ResultSet select(String sql, Object...keys){
        //1.连接
        ResultSet rs = null;
        try {
            Connection conn = getCoon();
            //2.执行对象
            PreparedStatement pst = conn.prepareStatement(sql);
            //3.遍历keys
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }
            //4.执行sql地结果集
            rs = pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //5.返回结果集
        return rs;
    }
    //4.通用update的方法
    public static int update(String sql, Object...keys) {
        //1.连接
        int rs = 0;
        try {
            Connection conn = getCoon();
            //2.执行对象
            PreparedStatement pst = conn.prepareStatement(sql);
            //3.遍历keys
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i + 1), keys[i]);
            }
            //4.执行sql地结果集
            rs = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
}
